﻿// CSellDlg.cpp: 实现文件
//

#include "pch.h"
#include "SalaryManagement.h"
#include "CSellDlg.h"
#include"InfoFile.h"


// CSellDlg

IMPLEMENT_DYNCREATE(CSellDlg, CFormView)

CSellDlg::CSellDlg()
	: CFormView(IDD_SELL)
	, m_price(0)
	, m_left(0)
	, m_number(0)
	, m_sellInfo(_T(""))
{

}

CSellDlg::~CSellDlg()
{
}

void CSellDlg::DoDataExchange(CDataExchange* pDX)
{
	CFormView::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_COMBO1, m_combo);
	DDX_Text(pDX, IDC_EDIT1, m_price);
	DDX_Text(pDX, IDC_EDIT2, m_left);
	DDX_Text(pDX, IDC_EDIT6, m_number);
	DDX_Text(pDX, IDC_EDIT3, m_sellInfo);
}

BEGIN_MESSAGE_MAP(CSellDlg, CFormView)
	ON_CBN_SELCHANGE(IDC_COMBO1, &CSellDlg::OnCbnSelchangeCombo1)
	ON_BN_CLICKED(IDC_BUTTON3, &CSellDlg::OnBnClickedButton3)
	ON_BN_CLICKED(IDC_BUTTON4, &CSellDlg::OnBnClickedButton4)
END_MESSAGE_MAP()


// CSellDlg 诊断

#ifdef _DEBUG
void CSellDlg::AssertValid() const
{
	CFormView::AssertValid();
}

#ifndef _WIN32_WCE
void CSellDlg::Dump(CDumpContext& dc) const
{
	CFormView::Dump(dc);
}
#endif
#endif //_DEBUG


// CSellDlg 消息处理程序


void CSellDlg::OnInitialUpdate()
{
	CFormView::OnInitialUpdate();

	// TODO: 在此添加专用代码和/或调用基类

	//初始化下拉框
	CInfoFile file;
	//file.WriteDocline();
	file.ReadDocline();
	for (list<msg>::iterator it = file.ls.begin(); it != file.ls.end(); it++) {
		//遍历商品容器  把容器名称放到下拉框中
		m_combo.AddString(CString(it->name.c_str()));
	}
	//默认选中第一个商品
	m_combo.SetCurSel(0);

	OnCbnSelchangeCombo1();

}


void CSellDlg::OnCbnSelchangeCombo1()
{
	// TODO: 在此添加控件通知处理程序代码
	//切换商品触发的事件
	int index = m_combo.GetCurSel();
	CString str;
	m_combo.GetLBText(index, str);


	//
	CInfoFile file;
	file.ReadDocline();
	for (list<msg>::iterator it = file.ls.begin(); it != file.ls.end(); it++) {
		
		if (CString(it->name.c_str()) == str) {
			m_price = it->price;
			m_left = it->num;
			UpdateData(FALSE);
		}
	}
}


void CSellDlg::OnBnClickedButton3()
{
	// TODO: 在此添加控件通知处理程序代码

	//购买功能实现
	UpdateData(TRUE);
	if (m_number <= 0) {
		MessageBox(L"购买数量是负数");
		return;
	}
	if (m_number > m_left) {
		MessageBox(L"购买数量大于库存");
		return;
	}
	int index = m_combo.GetCurSel();
	CString str;
	m_combo.GetLBText(index, str);

	CInfoFile file;
	file.ReadDocline();
	for (list<msg>::iterator it = file.ls.begin(); it != file.ls.end(); it++) {

		if (CString(it->name.c_str()) == str) {
			it->num -= m_number;
			m_left = it->num;

			//告诉用户具体信息
			CString sstr;
			sstr.Format(_T("商品：%s \r\n单价：%d \r\n个数：%d \r\n总价：%d \r\n"), str, m_price, m_number, m_price * m_number);

			m_sellInfo = sstr;
			UpdateData(FALSE);
			MessageBox(L"购买成功");
			m_number = 0;
		}
	}
	//把最新的数据写到文件中
	file.WriteDocline();





	m_sellInfo.Empty();
	UpdateData(FALSE);

}


void CSellDlg::OnBnClickedButton4()
{
	// TODO: 在此添加控件通知处理程序代码
	m_number = 0;
	UpdateData(FALSE);

	m_combo.SetCurSel(0);
	OnCbnSelchangeCombo1();
}
